<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace addons\equip\user\controller;

use addons\equip\model\EquipOrder as EquipOrderM;

/**
 * Class EquipOrder
 * @package addons\equip\user\controller
 */
class EquipOrder extends \web\user\controller\AddonUserBase {


    public function index() {
        return $this->fetch();
    }

    /**
     * 装备列表
     * @return array
     */
    public function loadList() {
        $keyword = $this->_get('keyword');
        $js_order_sn = $this->_get('js_order_sn');
        $js_username = $this->_get('js_username');
        $status = $this->_get('status');
        $startDate = $this->_get('startDate');
        $endDate = $this->_get("endDate");
        $filter = ' 1=1';
        if ($startDate != null && $endDate != null)
            $filter .= ' and (a.create_time >= \'' . $startDate . ' 00:00:00\' and a.create_time <= \'' . $endDate . ' 23:59:59\')';
        elseif ($startDate != null)
            $filter .= ' and (a.create_time >= \'' . $startDate . ' 00:00:00\')';
        elseif ($endDate != null)
            $filter .= ' and (a.create_time <= \'' . $endDate . ' 23:59:59\')';

        if ($keyword != null) {
            $filter .= ' and b.phone like \'%' . $keyword . '%\'';
        }
        if ($js_order_sn != null) {
            $filter .= ' and a.order_sn like \'%' . $js_order_sn . '%\'';
        }
        if ($js_username != null) {
            $filter .= ' and b.username like \'%' . $js_username . '%\'';
        }
        if ($status != null) {
            $filter .= ' and a.status = '. $status;
        }
        $m = new EquipOrderM;
        $total = $m->getEquipOrderTotal($filter);
        $fields = 'a.*,b.username,b.phone,e.equip_name';
        $rows = $m->getEquipOrderList($this->getPageIndex(), $this->getPageSize(), $filter, $fields, 'a.id desc');
        return $this->toDataGrid($total, $rows);
    }

    /**
     *解冻账号
     * @return array|mixed|string
     */
    public function endOrder(){
        $id = $this->_post('id');
        $equipOrderM = new EquipOrderM;
        $status = $equipOrderM->getDetail($id,'status')['status'];
        try {
            if($status == 1) return $this->failData('当前订单已结束，请勿重复提交');
            $res = $equipOrderM->where(['id' => $id])->update(['status' => 1, 'update_time' => NOW_DATETIME]);
            if(!$res){
                return $this->failData('结束失败');
            }
            //添加管理日志
            $this->addLog(self::LOG_EDIT, 'Equip', [], $id, '结束矿机订单');
            return $this->successData();

        } catch (\Exception $e) {
            return $this->failData($e->getMessage());
        }
    }

    public function add_equip_1() {
        if (IS_POST) {
            //去除信息中的空格
            $user_id = trim($this->_post('user_id',true));
            if($user_id == '') return $this->failData('请选择用户');
            $e_id = trim($this->_post('e_id',true));
            if($e_id == '') return $this->failData('请选择任务包');
            $amount = trim($this->_post('amount',true));
            if($amount == '') return $this->failData('请输入金额');
            try {
                $equipM = new \addons\equip\model\Equip();
                $equipOrderM = new \addons\equip\model\EquipOrder();
                $equip_data = $equipM->getDetail($e_id);
                $add_data = [
                    'e_id' => $e_id,
                    'user_id' => $user_id,
                    'order_sn' => 'Urw'.date('YmdHis').rand(100000,999999),
                    'amount' => $amount,
                    'total_amount' => round(($amount * $equip_data['earnings_tax'] / 100), 2),
                    'earnings_tax' => $equip_data['earnings_tax'],
                    'cycle_number' => $equip_data['cycle_number'],
                    'kof_day_tax' => $equip_data['kof_day_tax'],
                    'days_release' => round((round(($amount * $equip_data['earnings_tax'] / 100), 2) / $equip_data['cycle_number']),2),
                    'hashrate_amount' => $equip_data['hashrate_amount'],
                    'type' => $equip_data['type'],
                    'limit_num' => $equip_data['limit_num'],
                    'release_balance_type' => $equip_data['release_balance_type'],
                    'create_time' => NOW_DATETIME,
                    'end_time' => date("Y-m-d H:i:s", (time() + ($equip_data['cycle_number'] * 86400))),
                ];

                $re_add = $equipOrderM->add($add_data);
                if(!$re_add) {
                    return $this->failData('提交失败，请稍后再试');
                }
                return $this->successData();
            } catch (\Exception $ex) {
                return $this->failData($ex->getMessage());
            }
        } else {
            $list = (new \addons\member\model\MemberAccountModel())->field('id,username,phone')->where(['logic_delete' => 0, 'is_auth' => 1])->order('id asc')->select();
            $this->assign('user_list', json_encode($list, 256));
            $equip_list = (new \addons\equip\model\Equip())->field('id,equip_name')->where(['type' => 2])->order('id asc')->select();
            $this->assign('equip_list', json_encode($equip_list, 256));
            $this->assign('id', '');
            return $this->fetch();
        }
    }

    public function add_equip_2() {
        if (IS_POST) {
            //去除信息中的空格
            $user_id = trim($this->_post('user_id',true));
            if($user_id == '') return $this->failData('请选择用户');
            $e_id = trim($this->_post('e_id',true));
            if($e_id == '') return $this->failData('请选择任务包');
            $amount = trim($this->_post('amount',true));
            if($amount == '') return $this->failData('请输入数量');
            try {
                $equipM = new \addons\equip\model\Equip();
                $equipOrderM = new \addons\equip\model\EquipOrder();
                $equip_data = $equipM->getDetail($e_id);

                //获得当前任务包数量
                $existing_number = $equipOrderM->where(['user_id' => $user_id, 'status' => 0, 'e_id' => $e_id])->count();
                if(($existing_number + $amount) > $equip_data['limit_num']){
                    return $this->failData('当前用户数量已超出当前任务包上限');
                }

                $add_data = [
                    'e_id' => $e_id,
                    'user_id' => $user_id,
                    'order_sn' => 'Drw'.date('YmdHis').rand(100000,999999),
                    'amount' => $equip_data['min_amount'],
                    'total_amount' => round(($equip_data['min_amount'] * $equip_data['earnings_tax'] / 100), 2),
                    'earnings_tax' => $equip_data['earnings_tax'],
                    'cycle_number' => $equip_data['cycle_number'],
                    'kof_day_tax' => $equip_data['kof_day_tax'],
                    'days_release' => round((round(($equip_data['min_amount'] * $equip_data['earnings_tax'] / 100), 2) / $equip_data['cycle_number']),2),
                    'hashrate_amount' => $equip_data['hashrate_amount'],
                    'type' => $equip_data['type'],
                    'limit_num' => $equip_data['limit_num'],
                    'release_balance_type' => $equip_data['release_balance_type'],
                    'create_time' => NOW_DATETIME,
                    'end_time' => date("Y-m-d H:i:s", (time() + ($equip_data['cycle_number'] * 86400))),
                ];

                for($i=1; $i<=$amount; $i++){
                    $re_add = $equipOrderM->add($add_data);
                    if(!$re_add) {
                        return $this->failData('购买失败，请稍后再试');
                    }
                }
                return $this->successData();
            } catch (\Exception $ex) {
                return $this->failData($ex->getMessage());
            }
        } else {
            $list = (new \addons\member\model\MemberAccountModel())->field('id,username,phone')->where(['logic_delete' => 0, 'is_auth' => 1])->order('id asc')->select();
            $this->assign('user_list', json_encode($list, 256));
            $equip_list = (new \addons\equip\model\Equip())->field('id,equip_name')->where(['type' => 3])->order('id asc')->select();
            $this->assign('equip_list', json_encode($equip_list, 256));
            $this->assign('id', '');
            return $this->fetch();
        }
    }


    public function add_equip_3() {
        if (IS_POST) {
            //去除信息中的空格
            $user_id = trim($this->_post('user_id',true));
            if($user_id == '') return $this->failData('请选择用户');
            $e_id = trim($this->_post('e_id',true));
            if($e_id == '') return $this->failData('请选择任务包');
            $amount = trim($this->_post('amount',true));
            if($amount == '') return $this->failData('请输入金额');
            try {
                $equipM = new \addons\equip\model\Equip();
                $equipOrderM = new \addons\equip\model\EquipOrder();
                $equip_data = $equipM->getDetail($e_id);

                $add_data = [
                    'e_id' => $e_id,
                    'user_id' => $user_id,
                    'order_sn' => 'Krw'.date('YmdHis').rand(100000,999999),
                    'amount' => $amount,
                    'total_amount' => $amount + (round(($amount * $equip_data['earnings_tax'] / 100), 4)),
                    'earnings_tax' => $equip_data['earnings_tax'],
                    'cycle_number' => $equip_data['cycle_number'],
                    'kof_day_tax' => $equip_data['kof_day_tax'],
                    'days_release' => round((round(($amount * $equip_data['earnings_tax'] / 100), 2) / $equip_data['cycle_number']),2),
                    'hashrate_amount' => $equip_data['hashrate_amount'],
                    'type' => $equip_data['type'],
                    'limit_num' => $equip_data['limit_num'],
                    'release_balance_type' => $equip_data['release_balance_type'],
                    'create_time' => NOW_DATETIME,
                    'end_time' => date("Y-m-d H:i:s", (time() + ($equip_data['cycle_number'] * 86400))),
                ];

                $re_add = $equipOrderM->add($add_data);
                if(!$re_add) {
                    return $this->failData('提交失败，请稍后再试');
                }
                return $this->successData();
            } catch (\Exception $ex) {
                return $this->failData($ex->getMessage());
            }
        } else {
            $list = (new \addons\member\model\MemberAccountModel())->field('id,username,phone')->where(['logic_delete' => 0, 'is_auth' => 1])->order('id asc')->select();
            $this->assign('user_list', json_encode($list, 256));
            $equip_list = (new \addons\equip\model\Equip())->field('id,equip_name')->where(['type' => 4])->order('id asc')->select();
            $this->assign('equip_list', json_encode($equip_list, 256));
            $this->assign('id', '');
            return $this->fetch();
        }
    }

//    /**
//     * 装备添加和修改
//     * @return array|mixed|string
//     */
//    public function edit() {
//        if (IS_POST) {
//            $data = $_POST;
//            $id = $data['id'];
//            $data['update_time'] = NOW_DATETIME;
//            $m = new EquipOrderM;
//            try {
//                if (empty($id)) {
//                    unset($data['id']);
//                    $data['create_time'] = NOW_DATETIME;
//                    $ret = $m->add($data, false);
//                } else {
//                    $where['id'] = $id;
//                    $ret = $m->save($data, $where, null, false);
//                }
//
//                //添加管理日志
//                $this->addLog(self::LOG_EDIT, 'EquipOrder', $data, 0, '装备订单');
//                return $this->successData();
//            } catch (\Exception $e) {
//                return $this->failData($e->getMessage());
//            }
//        } else {
//            $id = $this->_get('id');
//            $this->assign('id', $id);
//            $this->setLoadDataAction('loadData');
//            return $this->fetch();
//        }
//    }


    public function loadData() {
        $id = $this->_get('id');
        $m = new EquipOrderM;
        $data = $m->getDetail($id);
        return $data;
    }

    public function select_equip(){
        return $this->fetch();
    }

    public function loadSelectEquip(){
        $keyword = $this->_get('keyword');
        $filter = ' type = 2 ';
        if ($keyword != null) {
            $filter .= ' and equip_name like \'%' . $keyword . '%\'';
//             $filter .= ' and username like \'%' . $keyword . '%\'';
        }
        $m = new \addons\equip\model\Equip();
        $total = $m->getTotal($filter);
        $rows = $m->getDataList($this->getPageIndex(), $this->getPageSize(), $filter);
        return $this->toDataGrid($total, $rows);
    }


//    /**
//     * 删除
//     */
//    public function del() {
//        $id = intval($this->_get('id'));
//        if (!empty($id)) {
//            $m = new EquipOrderM;
//            try {
//                $res = $m->deleteData($id);
//                if ($res > 0) {
//                    return $this->successData();
//                } else {
//                    return $this->failData('删除失败');
//                }
//            } catch (\Exception $e) {
//                return $this->failData($e->getMessage());
//            }
//        } else {
//            return $this->failData('删除失败，参数有误');
//        }
//    }

}
